package com.yesun.task.pipeline.handler.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yesun.core.util.FileUtils;
import com.yesun.server.mdp.service.client.impl.DefaultClient;
import com.yesun.task.pipeline.common.Constant;
import com.yesun.task.pipeline.domain.dto.JobDto;
import com.yesun.task.pipeline.domain.dto.TaskDto;
import com.yesun.task.pipeline.handler.Executor;
import com.yesun.task.pipeline.handler.Handler;
import com.yesun.task.pipeline.handler.Loader;
import com.yesun.task.pipeline.worker.ParallelWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

//每日成交数据Handler，粒度股票+dt
@Slf4j
public class HistoryDayHandler extends Handler {

    static DefaultClient client = new DefaultClient();
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    static SimpleDateFormat shortSdf = new SimpleDateFormat("yyyyMMdd");
    static String TODAY = shortSdf.format(Calendar.getInstance().getTime());
    static Loader loader;

    public HistoryDayHandler(JobDto jobDto) {
        super(jobDto);
    }

    @Override
    public Loader getLoader() {
        if(loader == null) {
            //实例化
            loader = new Loader() {
                @Override
                public void load(BlockingQueue queue) {
                    log.info("加载每日成交数据采集任务...");
                    int pagesize = 6000; //一次性取出所有数据
                    //转义：/ = %7C， ，=%2C
                    //股票历史日数据
                    //https://push2his.eastmoney.com/api/qt/stock/kline/get?cb=jQuery351005532679000634544_1694667009135&secid=0.300560&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1,f2,f3,f4,f5,f6&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61&klt=101&fqt=1&end=20500101&lmt=1365&_=1694667009186
                    String url = "http://55.push2.eastmoney.com/api/qt/clist/get?cb=jQuery11240523801592311929_1692314671179&pn=1&pz="+pagesize+"&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&wbp2u=%7C0%7C0%7C0%7Cweb&fid=f3&fs=m:0+t:6%2Cm:0+t:80%2Cm:1+t:2%2Cm:1+t:23%2Cm:0+t:81+s:2048&fields=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6%2Cf7%2Cf8%2Cf9%2Cf10%2Cf12%2Cf13%2Cf14%2Cf15%2Cf16%2Cf17%2Cf18%2Cf20%2Cf21%2Cf23%2Cf24%2Cf25%2Cf22%2Cf11%2Cf62%2Cf128%2Cf136%2Cf115%2Cf152&_=1692314671197";
                    TaskDto taskDto = new TaskDto();
                    taskDto.setJobName(jobDto.getJobName());
                    taskDto.setName("每日成交数据采集任务");
                    taskDto.setTag(Constant.JOB_TAG_DAY);

                    Map<String,String> map = new HashMap<>();
                    map.put("url", url);
                    map.put("saveTo", "/df_day/all_day_"+ shortSdf.format(new Date()) +".csv");//暂时只支持保存到磁盘
                    taskDto.setMap(map);


                    //加入MAP_TASK
                    ParallelWorker.MAP_TASK.put(taskDto.getName(), taskDto.getJobName());

                    queue.offer(taskDto);
                    log.info("添加子任务：" + taskDto.getName());
                }
            };
        }
        return loader;
    }

    @Override
    public Executor getExecutor() {
        return new Executor() {
            @Override
            public void execute(TaskDto taskDto) {
                //执行task的采集
                log.info("execute：" + taskDto.getName());
                long start = System.currentTimeMillis();
                try {
                    StringBuffer stringBuffer = new StringBuffer();
                    CloseableHttpClient httpclient = HttpClients.createDefault();
                    CloseableHttpResponse response = null;
                    HttpGet httpGet = new HttpGet(taskDto.getMap().get("url"));
                    try {
                        response = httpclient.execute(httpGet);
                        HttpEntity entity = response.getEntity();
                        Header[] headers = response.getAllHeaders();
                        if (entity != null) {
                            InputStream inputStream = entity.getContent();
                            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                            String line;
                            while ((line = reader.readLine()) != null) {
                                stringBuffer.append(line);
                            }
                        }
                    } catch (org.apache.http.client.ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if(response!=null) {
                            try {
                                response.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    long requestEnd = System.currentTimeMillis();
                    log.info("http request time:" + (requestEnd-start));
                    String content = stringBuffer.toString();

                    content = content.substring(content.indexOf("{"), content.lastIndexOf("}")+1);
                    log.debug("content:"+content);
                    /** 数据结构
                     open  price  high  low  vol    amount       amplitude      change_pct      change,   change_hands
                     "2023-09-13,19.15,18.79,20.14,18.75,184668,356172988.00,7.47,           0.97,           0.18,     9.88",
                     **/

                    StringBuffer sb = new StringBuffer("采集日期,交易日期,股票代码,股票名称,最新价,涨跌幅,涨跌额,成交量(手),成交额,振幅,换手率,市盈率(当日动态),量比,最高,最低,今开,昨收,总市值,流通市值,市净率,市盈率TTM\n"); //股价最好从其他表获取
                    JSONArray jsonArray = JSONObject.parseObject(content)
                            .getJSONObject("data")
                            .getJSONArray("diff");
                    jsonArray.stream()
                            .forEach(line -> {
                                //遍历每一条记录
                                JSONObject obj = (JSONObject)line;
                                if(obj.getString("f2").equals("-"))
                                    return;
                                sb.append(TODAY + "," + TODAY + ","
                                        + obj.getString("f12") + ","
                                        + obj.getString("f14") + ","
                                        + obj.getString("f2") + ","
                                        + obj.getString("f3") + ","
                                        + obj.getString("f4") + ","
                                        + obj.getString("f5") + ","
                                        + obj.getString("f6") + ","
                                        + obj.getString("f7") + ","
                                        + obj.getString("f8") + ","
                                        + obj.getString("f9") + ","
                                        + obj.getString("f10").replace("-","0") + ","
                                        + obj.getString("f15") + ","
                                        + obj.getString("f16") + ","
                                        + obj.getString("f17") + ","
                                        + obj.getString("f18") + ","
                                        + obj.getString("f20") + ","
                                        + obj.getString("f21") + ","
                                        + obj.getString("f23") + ","
                                        + obj.getString("f115") + ",\n");


//                                String[] arr = line.toString().split(",");
//                                sb.append(TODAY + "," + arr[11] + "," + arr[13] + "," +  arr[1] + "," + arr[2] + "," + arr[3] + "," + arr[4] + "," + arr[5] + "," + arr[6] + "," + arr[7] + "," + arr[8] + "," + arr[9]
//                                        + "," + arr[14] + "," + arr[15] + "," + arr[16]  + "," + arr[17]  + "," + arr[18]  + "," + arr[19]  + "," + arr[21]  + "," + arr[25] +",\n");
                            });
                    long processEnd = System.currentTimeMillis();
                    log.info("process content time:" + (processEnd-requestEnd));

                    //saveto
                    FileUtils.saveCsv(Constant.BASE_PATH + taskDto.getMap().get("saveTo"), sb.toString(), "UTF-8");
                    long saveEnd = System.currentTimeMillis();
                    log.info("save csv file time:" + (saveEnd-processEnd));

                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
